import urllib
import json
import jsTool

urlread = lambda url : urllib.urlopen(url).read()

def r2o(request):
    try : 
        jResult = urlread(request)
        obj =  json.loads(jResult)
        return obj
    except Exception , e :
        print e
        print 'cannot get the json object form'
        print jResult

def getCollectInfo(account , cat ):
    l=1
    start=0

    catSet = {}
    while(l>0) :
        request = 'http://api.douban.com/people/'+account 
        request +=  '/collection?cat=' + cat + '&alt=json&start-index=' 
        request +=  str(start) + '&max-results=50'
        request +=  '&apikey=0fab481d0f57370e2f01d8572e05a52a'
        obj = r2o(request)
        #print obj
        entry=obj[u'entry']
        for k in entry:
            pic = k[u'db:subject'][u'link'][2][u'@href']
            print pic
            link = k[u'db:subject'][u'link'][1][u'@href']
            print link
            title = k[u'title'][u'$t']
            print title
            catSet[link]={'title':title,'pic':pic}
            print '------------------------'
        start +=50
        l=len(entry)

    
    return catSet

def main(account):
    collectSet={}
    kind = ['movie','book','music']
    for k in kind:
        collectSet[k]=getCollectInfo(account,k)
    print collectSet
    jsTool.o2j(collectSet,'collectSet.json')


if __name__=='__main__':
    account = 'nilin56'
    collectSet={}
    kind = ['movie','book','music']
    for k in kind:
        collectSet[k]=getCollectInfo(account,k)
    #print collectSet
    jsTool.o2j(collectSet,'collectSet.json')

    
